package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN_ADDR = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WeChatProperties weChatProperties;

    @Autowired
    UserMapper userMapper;

    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        // 获取授权码
        String code = userLoginDTO.getCode();
        // 获取唯一表示
        String openId = getOpenId(code);
        // 如果返回的为null,就说明错误了
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.findByOpenId(openId);

        if (user == null) {
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }
        return user;
    }

    private String getOpenId(String code) {
        try {
            // 获取openid需要通过key value形式的参数获取,我们封装到map集合中
            HashMap<String, String> openMap = new HashMap<>();
            openMap.put("appid", weChatProperties.getAppid());
            openMap.put("secret", weChatProperties.getSecret());
            openMap.put("js_code", code);
            openMap.put("grant_type", "authorization_code");
            // 通过java请求把请求的地址和参数传进去
            String jsonStr = HttpClientUtil.doGet(WX_LOGIN_ADDR, openMap);
            // 把获取到的json格式的String转换成json对象,通过map集合
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(jsonStr, Map.class);
            // 通过get获取到map中的openid然后返回
            return (String) map.get("openid");
        } catch (JsonProcessingException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}
